package com.lazyframework.security.admin.configuration;

import com.lazyframework.security.admin.access.DefaultRbacServiceImpl;
import com.lazyframework.security.admin.access.RbacService;
import com.lazyframework.security.admin.authentication.LoginLogService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.userdetails.UserDetails;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * Create by lazy in #{date} #{time}
 */
@Configuration
public class AutowiredBeanConfigurer {

    private static final Logger logger = LoggerFactory.getLogger(LoginLogService.class);

    @Bean
    @ConditionalOnMissingBean(RbacService.class)
    public RbacService rbacService() {
        return new DefaultRbacServiceImpl();
    }

    @Bean
    @ConditionalOnMissingBean(LoginLogService.class)
    public LoginLogService loginLogService() {
        logger.debug("Login log service is missing, default log service will be enable!");
        return (request, response, authentication) -> {
            UserDetails userDetails = (UserDetails) authentication.getPrincipal();
            logger.info("\nLoginInfo = {user: {}, ip: {}, time: {}}",
                    userDetails.getUsername(),
                    request.getRemoteAddr(),
                    LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        };
    }

}
